import React, {useEffect, useState} from 'react';
import { Form, Button, DatePicker,TreeSelect,Upload,Input, Modal,Row,message, Col} from 'antd';
import { connect } from 'umi';
import moment from 'moment';
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from '@/utils/upload'
import SelectUserModal from "@/pages/components/SelectUserModal";
import EditOvertimeSporadicTable from "./EditOvertimeSporadicTable";
import { PlusOutlined } from '@ant-design/icons';
import store from 'store2';

const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 7 },
};
const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const AddForm = (props) => {
  const { onSubmit, onCancel, loading,visible,currentUser} = props;
  const [form] = Form.useForm();
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [addUserList,setAddUserList] = useState([]);
  const [protocolUserItems,setProtocolUsers] = useState([]);

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1){
        urls.splice(index, 1);
        setFileUploadUrls(urls);
      }
    },
  };

  useEffect(() => {
    if(currentUser && visible){
      const fieldsValue = store(`attendance-overtimeSporadic-` + currentUser.mobile);
      if(fieldsValue){
        form.setFieldsValue({...fieldsValue,overworkTime:moment(fieldsValue.overworkTime)});
        setAddUserList(fieldsValue.list || []);
        let temp = [];
        fieldsValue.uploadFile.fileList?.map(item => {temp.push(item.response);});
        setFileUploadUrls(temp);
        uploadedFiles = fieldsValue.uploadFile.fileList;
      }else{
        form.setFieldsValue({oprationId:currentUser.usercode,oprationName:currentUser.name,orgName:currentUser.orgname,
          unitName:currentUser.department,jobName:currentUser.jobname
        });
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    uploadedFiles = [];
    setFileUploadUrls([]);
    setAddUserList([]);
    setProtocolUsers([]);
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    let fileUploadUrlsStr = '';
    fileUploadUrls.forEach(item => {
      if (item){
        if (fileUploadUrlsStr === ''){
          fileUploadUrlsStr += item;
        }else {
          fileUploadUrlsStr += ',' + item;
        }
      }
    });
    onSubmit({
      ...fieldsValue,
      uploadFile:fileUploadUrlsStr,
      list:protocolUserItems
    });
    uploadedFiles = [];
    setFileUploadUrls([]);
    setAddUserList([]);
    setProtocolUsers([]);
  };

  const confirmSelectedUsers = (values) =>{
    setAddUserList(values);
    setUserModalVisible(false);
  };

  const saveProtocolUser = (values) => {
    let newProtocolUsers = [...values];
    setProtocolUsers(newProtocolUsers);
  };

  const onFormSave = async () => {
    const fieldsValue = await form.validateFields();
    store(`attendance-overtimeSporadic-` + currentUser.mobile,{...fieldsValue,list:protocolUserItems});
    message.success("信息暂存成功！");
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="oprationId" label="申请人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="oprationName" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgName" label="公司" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitName" label="部门" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobName" label="岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}></Col>
          <Col {...colStyle}>
            <FormItem name="overworkName" label="加班名称" rules={[{required: true, message: '加班名称不能为空'}]}>
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="overworkTime" label="加班时间" rules={[{required: true, message: '加班时间不能为空'}]}>
              <DatePicker picker="month" format="YYYY-MM" className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="uploadFile" label="上传附件" rules={[{required: true, message: '附件不能为空'}]}>
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24} style={{paddingRight: 12,paddingLeft:40}}>
            <FormItem name="list" style={{marginBottom: '6px'}}>
              <EditOvertimeSporadicTable addUserList={addUserList} protocolUserItems={protocolUserItems} saveFunction={saveProtocolUser}/>
            </FormItem>
          </Col>
          {
            <Col span={24} style={{paddingRight: 12,paddingLeft:40}}>
              <Button style={{width: '100%',marginBottom: 24}} type="dashed" onClick={()=>setUserModalVisible(true)}>
                <PlusOutlined/>
                新增成员
              </Button>
            </Col>
          }
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button onClick={() => onFormSave()}>暂存</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      width={'70%'}
      destroyOnClose
      centered
      title={`零星加班申请`}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
      <SelectUserModal
        selectType={1}
        visible={userModalVisible}
        handleOk={confirmSelectedUsers}
        handleCancel={()=>setUserModalVisible(false)}
      />
    </Modal>
  )
};

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(AddForm);
